package com.yhny.lykj.yuhannongye.tools;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import com.longsichao.lscframe.tools.LSCLog;

import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * ImageSelector
 * Created by LSC on 2015/9/30.
 */
public final class ImageSelector {
    private static final int UserPicCamera = 0x299a;
    private static final int UserPicAlbum = 0x299b;
    private static final int UserPicCrop = 0x299c;
    private static final String TAG = "ImageSelector";

    private String cameraPath;
    private String cropPicPath;
    private Activity activity;
    private boolean isCrop;
    private OnImageSelectedListener listener = null;
    private int outX = 150;
    private int outY = 150;

    public ImageSelector(Activity activity, boolean isCrop, OnImageSelectedListener l) {
        this.activity = activity;
        this.isCrop = isCrop;
        this.listener = l;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case UserPicAlbum:
                if (data == null) {
                    Log.w(TAG, "Pic image result null.");
                    break;
                }
                if (isCrop) {
                    startPhotoZoom(data.getData());
                } else if (listener != null) {
                    listener.onImageSelected(data.getData());
                } else {
                    Log.w(TAG, "OnImageSelectedListener not set.");
                }
                break;
            case UserPicCamera:
                File temp = new File(cameraPath);
                if (temp.length() > 0) {
                    if (isCrop) {
                        startPhotoZoom(Uri.fromFile(temp));
                    } else if (listener != null) {
                        listener.onImageSelected(Uri.fromFile(temp));
                    } else {
                        Log.w(TAG, "OnImageSelectedListener not set.");
                    }
                } else {
                    Log.i(TAG, "Camera canceled.");
                }
                break;
            case UserPicCrop:
                if (data == null) {
                    Log.w(TAG, "Crop image result null.");
                    break;
                }
                if (listener != null) {
                    listener.onImageSelected(Uri.parse(cropPicPath));
                } else {
                    Log.w(TAG, "OnImageSelectedListener not set.");
                }
                break;
            default:
                Log.v(TAG, "requestCode=" + requestCode + ", resultCode=" + resultCode);
                break;
        }
    }

    public void fromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(intent, UserPicAlbum);
    }

    public void fromCamera() {
        cameraPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(cameraPath)));
        activity.startActivityForResult(intent, UserPicCamera);
    }

    public void setOutSize(int x, int y) {
        outX = x;
        outY = y;
    }

    private void startPhotoZoom(Uri uri) {
        cropPicPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".png";
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outX);
        intent.putExtra("outputY", outY);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(cropPicPath)));
        activity.startActivityForResult(intent, UserPicCrop);
    }

    //压缩图片大小
    public static byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 30) {
            LSCLog.d("options=" + options);
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
            if (options <= 0) {
                break;
            }
        }
        if (!image.isRecycled()) {
            image.recycle();
            image = null;
        }
        System.gc();
        return baos.toByteArray();
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
//        return bitmap;
    }

    public interface OnImageSelectedListener {
        void onImageSelected(Uri uri);
    }
}
